import {EventsEmit, EventsOnce} from "frontend/src/wailsjs/runtime"

import { nanoid } from "nanoid"

export enum Methods {
    POST = "POST",
    GET = "GET",
    HEAD = "HEAD",
    PUT = "PUT",
    DELETE = "DELETE",
    PATCH = "PATCH",
    OPTIONS = "OPTIONS",
}

export type UUID = string

export interface RequestConfig {
    url: string
    method: Methods,
    header?: Record<string, any>,
    params?: Record<string, any>,
    data?: any,
    timeout?: number,
    proxy?: boolean,
    channel?: UUID,
    debug?: false,
    certificate?: Certificate
}

export interface Certificate {
    rootCA: string
    clientCrt: string
    clientKey: string
}

export interface ResponseJson {
    Header: Record<string, string[]>,
    Status: number,
    Data: any,
    Error: any,
}

export interface Response {
    header: Record<string, string[]>,
    status: number,
    data: any,
    error: any,
    rawData: string,
}

export type Callback = (data: Response) => void;

export function request(config: RequestConfig) {
    return new Promise<Response>((resolve)=>{
        if (!config.channel) {
            config.channel = nanoid()
        }

        if (config.debug) {
            console.time(config.channel)
        }

        EventsOnce(config.channel, (data) => {
            data = data as ResponseJson
            if (config.debug) {
                console.timeEnd(config.channel)
            }

            try {
                let json = JSON.parse(data.Data)
                resolve({
                    data: json,
                    status: data.Status,
                    error: data.Error,
                    header: data.Header,
                    rawData: data.RawData
                })
            } catch (e) {
                resolve({
                    status: data.Status,
                    data: data.Data,
                    error: data.Error,
                    header: data.Header,
                    rawData: data.RawData
                })
            }
        })
        EventsEmit("request", JSON.stringify(config))
    })
}

(window as any).request = request
